<template>
  <div class="conten">
    <div class="prompt">
      <p>{{$t('monitor.tip')}}</p>
      <p>{{$t('call.batchExportTip')}}</p></div>
    <affix :label="$t('qualityCheck.condition')"></affix>
    <el-form>
      <el-form-item :label="$t('call.bAndETime')">
        <el-date-picker v-model="rangeTime"
                        type="datetimerange"
                        size="mini"
                        :editable = "false"
                        :picker-options="pickerOptions"
                        id="callExportPicker"
                        :placeholder="$t('public.timeRanges')"></el-date-picker></el-form-item>
      <el-form-item class="btn-group">
        <el-button @click = "rest"
                   class="primary_btn">{{$t('public.reset')}}</el-button>
        <el-button type="primary"
                   @keyup.native.enter="search"
                   @click="getTableList1"
                   class="primary_btn">{{$t('public.search2')}}</el-button></el-form-item>
    </el-form>
    <affix :label="$t('call.queryResult')"></affix>
    <batch-export-list :data = "tableData"
                       :tableLoading = "tableLoading"
                       @cancelTask = "cancelTask"
                       :currentPage = "currentPage"
                       @turnPage = "turnPage"></batch-export-list>
  </div>
</template>
<script>
  // 此组件是批量导出录音任务管理
  import Pagination from '@/components/public-modules/card/Pagination'
  import affix from '../../ui-modules/affix/Affix.vue'
  import BatchExportList from '@/components/public-modules/batch-export-list/BatchExportList'
  import {getDateTime, getCache} from '@/utils/m7Utils.js'
  export default {
    data () {
      return {
        isSearch: false,
        tableData: {},
        tableLoading: false,
        currentPage: 1,
        pickerOptions: {
          shortcuts: [{
            text: this.$t('sms.thisOneWeek'),
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: this.$t('sms.thisOneMonth'),
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: this.$t('sms.thisThreeMonth'),
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }]
        },
        rangeTime: []
      }
    },
    methods: {
      getTableList1 () { // 查询
        this.isSearch = true
        if (this.currentPage === 1) {
          this.isSearch = false
        }
        this.currentPage = 1
        this.getTableList()
      },
      turnPage (val) { // 翻页
        this.currentPage = val
        if (this.isSearch && val < 2) {
          this.isSearch = false
          return
        }
        this.getTableList()
      },
      cancelTask (id) {
        this.$confirm(this.$t('call.confirmCancelTaskSuc'),  this.$t('public.tip'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('removeExportMonitorTask', id).then(resp => {
            if (resp.success) {
              this.$message.success(this.$t('call.cancelTaskSuc'))
              this.getTableList1()
            }
          })
        })
      },
      rest () {
        // 重置为[]: 如果为'' getDateTime()会报一个ERROR
        this.rangeTime = []
      },
      dealData (obj) {
        // 通过字段来判断显示什么字段存到state下，如果需要显示不同状态的颜色，就带一个class在子组件添加style
        obj.list.map(item => {
          item.paths = []
          let okDown = false
          for (let i in item.downloadUrlList) {
            if (item.downloadUrlList[i].includes('&')) {
              let path = item.downloadUrlList[i].split('&')[0]
              let paths = []
              if (path.includes(',')) {
                paths = path.split(',')
              } else {
                paths.push(path)
              }
              for (let j = 0; j < paths.length; j++) {
                if (item.downloadUrlList[i].includes(']') && item.downloadUrlList[i].includes('[')) {
                  if (i.indexOf('@@') > -1) {
                    let str = i.replace(/@@/g, '.')
                    item.paths.push({
                      downExplain: `PBX${str}[${paths[j].substring(paths[j].indexOf('[') + 1, paths[j].indexOf(']'))}]`,
                      address: paths[j]
                    })
                  } else {
                    item.paths.push({
                      downExplain: `PBX${i}[${paths[j].substring(paths[j].indexOf('[') + 1, paths[j].indexOf(']'))}]`,
                      address: paths[j]
                    })
                  }
                  okDown = true
                  item.isNoDown = false
                } else {
                  if (!okDown) {
                    item.noDowm = this.$t('call.noDownLoad')
                    item.isNoDown = true
                  } else {
                    item.isNoDown = false
                  }
                }
              }
            } else {
              if (i.indexOf('@@') > -1) {
                let str = i.replace(/@@/g, '.')
                item.paths.push({
                  downExplain: `PBX${str}`,
                  address: item.downloadUrlList[i]
                })
              } else {
                item.paths.push({
                  downExplain: `PBX${i}`,
                  address: item.downloadUrlList[i]
                })
              }
            }
          }
          if (item.status === 'ready') {
            item.state = this.$t('call.waitCompress')
            item.class = 'exportProcessing'
          } else {
            if (item.status === 'finish' && JSON.stringify(item.downloadUrlList).indexOf('portion') !== -1 && JSON.stringify(item.downloadUrlList).indexOf(']') !== -1 && !item.isNoDown) {
              item.state = this.$t('call.partFinish')
            } else {
              item.state = this.$t('public.finish')
            }
          }
          if (item.creator) {
            let createUser = getCache('agents', item.creator)
            let displayName = createUser.displayName || '--'
            let exten = createUser.exten || '--'
            item.createUser = displayName + '[' + exten + ']'
          } else {
            item.createUser = '--[--]'
          }
        })
        return obj
      },
      // 获取导出结果的数据, 此处需判断是否选择时间进行查询，如没有则不传"BEGIN_TIME"，"END_TIME"参数，
      // val默认为 1, 当前组件只有子组件传递翻页请求的时候才会改变val值
      getTableList () {
        let data = {
          page: this.currentPage,
          pageSize: 10,
          BEGIN_TIME: '',
          END_TIME: ''
        }
        if (this.rangeTime && this.rangeTime[0]) {
          data.BEGIN_TIME = getDateTime(this.rangeTime[0])
          data.END_TIME = getDateTime(this.rangeTime[1])
        } else {
          delete data.BEGIN_TIME
          delete data.END_TIME
        }
        this.tableLoading = true
        this.$store.dispatch('queryExportMonitorTask', data).then(resp => {
          if (resp.success) {
            this.tableData = this.dealData(resp)
            this.tableLoading = false
          } else {
            this.tableLoading = false
          }
        })
      }
    },
    components: {
      Pagination,
      affix,
      BatchExportList
    },
    beforeMount () {
      this.getTableList(1)
    }
  }
</script>
<style lang="stylus" rel="stylesheet/stylus" scoped>
  @import "../../../assets/common.styl"
    .conten
      padding 0px 16px 20px
      .ui-affix
        margin-top 32px
        padding-bottom 10px
      .el-form
        padding-left 16px
        .btn-group
          text-align right
      .prompt
        color $c-prompt
        margin-bottom 10px
</style>
